<template>
    <div class="chat-container">
        <div class="header">
            <h1>再生道环保交流平台</h1>
            <p class="slogan">让废物重获新生，让地球更添绿色</p>
        </div>
        
        <div class="chat-box">
            <div class="order-section">
                <h3><i class="el-icon-document"></i> 订单号</h3>
                <div class="order-input-group">
                    <el-input 
                        v-model="orderNum" 
                        placeholder="请输入订单号"
                        prefix-icon="el-icon-connection"
                        class="order-input"
                        clearable
                    ></el-input>
                    <el-button 
                        type="success" 
                        @click="fetchChatHistory"
                    >进入聊天</el-button>
                </div>
            </div>

            <div class="chat-section">
                <h3><i class="el-icon-message"></i> 聊天记录</h3>
                <div class="chat-content">
                    <div class="message-list" ref="messageList">
                        <div v-for="(msg, index) in messages" 
                             :key="index" 
                             :class="['message-item', msg.userId === userId ? 'message-right' : 'message-left']"
                        >
                            <div class="message-time">{{ formatMessageTime(msg.time) }}</div>
                            <div class="message-content" 
                                 :class="msg.userId === userId ? 'sent' : 'received'"
                            >
                                {{ msg.content }}
                            </div>
                        </div>
                    </div>
                    
                    <div class="input-area">
                        <el-input 
                            v-model="newMessage"
                            placeholder="输入消息..."
                            type="textarea"
                            :rows="3"
                            class="message-input"
                            @keyup.enter.native="sendMessage"
                            resize="none"
                        ></el-input>
                        <el-button 
                            type="success" 
                            @click="sendMessage" 
                            icon="el-icon-s-promotion"
                            class="send-button"
                            :disabled="!orderNum"
                        >
                            发送
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { Message } from 'element-ui'
import axios from 'axios'
import mqtt from 'mqtt'

interface ChatMessage {
    recyclingOrderNum: string;
    userId: number;
    content: string;
    senderType: string | null;
    msgType: string | null;
    time: string;
}

const orderNum = ref('')
const newMessage = ref('')
const messages = ref<ChatMessage[]>([])
const messageList = ref<HTMLElement | null>(null)
const userId = ref<number | null>(null)

// MQTT客户端
let client: mqtt.MqttClient | null = null

// 初始化MQTT连接
function initMqttConnection() {
    if (!orderNum.value) return
    
    const clientId = 'chat_' + Math.random().toString(16).substr(2, 8)
    const url = 'ws://127.0.0.1/mqtt'
    const options = {
        port: 8083,
        keepalive: 60,
        clientId: clientId,
        protocolId: 'MQTT',
        protocolVersion: 4 as 4,
        clean: true,
        connectTimeout: 30 * 1000,
        will: {
            topic: 'chat',
            payload: '用户断开连接',
            qos: 0,
            retain: false
        },
    }

    // 创建MQTT连接
    client = mqtt.connect(url, options)
    
    // 连接成功后订阅聊天主题
    client.on('connect', () => {
        console.log('MQTT连接成功')
        // 订阅该订单的聊天主题
        const topic = `chat/${orderNum.value}`
        client.subscribe(topic, { qos: 0 }, (error) => {
            if (!error) {
                console.log(`成功订阅聊天主题: ${topic}`)
            } else {
                console.error(`订阅聊天主题失败: ${error}`)
            }
        })
    })
    
    // 接收消息
    client.on('message', (topic, payload) => {
        try {
            const msg = JSON.parse(payload.toString())
            // 检查是否是当前订单的消息
            if (msg.recyclingOrderNum === orderNum.value) {
                // 检查是否是我们刚刚发送的临时消息
                const tempIndex = messages.value.findIndex(m => 
                    m._tempId && m.content === msg.content && m.userId === msg.userId
                )
                
                if (tempIndex >= 0) {
                    // 这是我们刚刚发送的消息，用服务器返回的消息替换临时消息
                    messages.value.splice(tempIndex, 1, msg)
                } else {
                    // 检查是否是重复消息
                    const isDuplicate = messages.value.some(existingMsg => 
                        existingMsg.time === msg.time && 
                        existingMsg.content === msg.content &&
                        existingMsg.userId === msg.userId
                    )
                    
                    if (!isDuplicate) {
                        // 这是一条新消息，添加到列表
                        messages.value.push(msg)
                        // 滚动到最新消息
                        setTimeout(() => {
                            if (messageList.value) {
                                messageList.value.scrollTop = messageList.value.scrollHeight
                            }
                        }, 50)
                    } else {
                        console.log('跳过重复消息:', msg)
                    }
                }
            }
        } catch (error) {
            console.error('解析消息失败:', error)
        }
    })
    
    // 错误处理
    client.on('error', (error) => {
        console.error('MQTT连接错误:', error)
        Message.error('聊天连接出错，请刷新页面重试')
    })
}

// 监听订单号变化，重新连接MQTT
watch(orderNum, (newVal, oldVal) => {
    if (newVal && newVal !== oldVal) {
        // 如果已有连接，先断开
        if (client) {
            client.end()
        }
        // 建立新连接
        initMqttConnection()
    }
})

// 格式化时间显示
function formatMessageTime(timeStr: string): string {
    const messageDate = new Date(timeStr)
    const now = new Date()
    
    const messageTime = messageDate.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    })

    // 同一天只显示时间
    if (isSameDay(messageDate, now)) {
        return messageTime
    }

    // 昨天显示"昨天 HH:mm"
    const yesterday = new Date(now)
    yesterday.setDate(yesterday.getDate() - 1)
    if (isSameDay(messageDate, yesterday)) {
        return `昨天 ${messageTime}`
    }

    // 其他日期显示完整格式
    return `${messageDate.getFullYear()}/${messageDate.getMonth() + 1}/${messageDate.getDate()} ${messageTime}`
}

function isSameDay(date1: Date, date2: Date): boolean {
    return date1.getFullYear() === date2.getFullYear() &&
           date1.getMonth() === date2.getMonth() &&
           date1.getDate() === date2.getDate()
}

// 获取聊天历史
async function fetchChatHistory() {
    if (!orderNum.value) {
        Message.warning('请输入订单号')
        return
    }
    axios.get('/userService/user/selectChatHistory', {
            params: {
                userId: localStorage.getItem('userId'),
                recyclingOrderNum: orderNum.value
            }
        }).then(resp=>{
            if (resp.data.code === 200) {
                // 解析每条消息字符串为对象
                messages.value = resp.data.data.map(msgStr => {
                    try {
                        return JSON.parse(msgStr)
                    } catch (error) {
                        console.error('解析消息失败:', error, msgStr)
                        return null
                    }
                }).filter(msg => msg !== null) // 过滤掉解析失败的消息
                
                if (messageList.value) {
                    messageList.value.scrollTop = messageList.value.scrollHeight
                }
                
                // 获取历史记录后初始化MQTT连接
                initMqttConnection()
            } else {
                Message.error(resp.data.message || '获取历史消息失败')
            }
        })
}

// 发送消息
async function sendMessage() {
    if (!newMessage.value.trim()) {
        Message.warning('请输入消息内容')
        return
    }
    
    const messageContent = newMessage.value.trim()
    newMessage.value = '' // 立即清空输入框
    
    // 创建临时消息对象
    const tempId = 'temp_' + Date.now()
    const localMessage = {
        recyclingOrderNum: orderNum.value,
        userId: userId.value,
        content: messageContent,
        time: new Date().toISOString(),
        _tempId: tempId // 添加临时ID用于后续去重
    }
    
    // 添加到本地消息列表
    messages.value.push(localMessage)
    
    // 滚动到最新消息
    setTimeout(() => {
        if (messageList.value) {
            messageList.value.scrollTop = messageList.value.scrollHeight
        }
    }, 50)
    
    // 发送到服务器
    try {
        const response = await axios.post('/userService/user/chat', {
            userId: localStorage.getItem('userId'),
            recyclingOrderNum: orderNum.value,
            content: messageContent
        })
        
        if (response.data.code !== 200) {
            // 发送失败，显示错误
            Message.error(response.data.message || '发送失败')
            
            // 从消息列表中移除临时消息
            messages.value = messages.value.filter(msg => msg._tempId !== tempId)
            
            // 恢复消息内容
            newMessage.value = messageContent
        }
    } catch (error) {
        console.error('发送消息错误:', error)
        Message.error('发送失败，请重试')
        
        // 从消息列表中移除临时消息
        messages.value = messages.value.filter(msg => msg._tempId !== tempId)
        
        // 恢复消息内容
        newMessage.value = messageContent
    }
}

// 检查登录状态
onMounted(() => {
    const storedUserId = localStorage.getItem('userId')
    if (storedUserId) {
        userId.value = Number(storedUserId)
    } else {
        Message.warning('请先登录')
        // 可以添加重定向到登录页面的逻辑
    }
    
    // 从路由参数或本地存储获取订单号
    // 在 Vue 2 中，我们需要使用 window.location 来获取查询参数
    const urlParams = new URLSearchParams(window.location.search);
    const queryOrderNum = urlParams.get('orderNum');
    
    if (queryOrderNum) {
        orderNum.value = queryOrderNum;
    } else {
        orderNum.value = localStorage.getItem('currentChatOrder') || '';
    }
    
    if(orderNum.value !== '' && orderNum.value !== null){
        fetchChatHistory()
    }
})

// 组件销毁时断开MQTT连接
onBeforeUnmount(() => {
    if (client) {
        client.end()
        console.log('MQTT连接已断开')
    }
})
</script>

<style scoped>
.chat-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
    min-height: 100vh;
    background-color: #f0f9eb;
}

.header {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px 0;
}

.header h1 {
    color: #67c23a;
    font-size: 2.5em;
    margin-bottom: 10px;
}

.slogan {
    color: #606266;
    font-size: 1.2em;
    font-style: italic;
}

.chat-box {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 30px;
}

.order-section {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid #f0f9eb;
}

.order-input-group {
    display: flex;
    gap: 10px;
    align-items: center;
    max-width: 500px;
}

.order-input {
    max-width: 500px;
}

.chat-section {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.chat-content {
    display: flex;
    flex-direction: column;
    height: 600px;
    background: #fafafa;
    border-radius: 8px;
    padding: 15px;
}

.message-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    background: white;
    border-radius: 8px;
    margin-bottom: 15px;
}

.message-item {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f9eb;
}

.message-left {
    text-align: left;
}

.message-right {
    text-align: right;
}

.message-time {
    color: #909399;
    font-size: 12px;
    margin-bottom: 5px;
}

.message-content {
    display: inline-block;
    max-width: 70%;
    padding: 10px 15px;
    border-radius: 8px;
    word-break: break-all;
    line-height: 1.5;
}

.message-content.received {
    background-color: #e0f7e9;
    color: #606266;
    border-radius: 12px 12px 12px 0;
}

.message-content.sent {
    background-color: #67c23a;
    color: white;
    border-radius: 12px 12px 0 12px;
}

h3 {
    color: #67c23a;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 8px;
}

h3 i {
    font-size: 1.2em;
}

.input-area {
    display: flex;
    gap: 10px;
    align-items: flex-start;
    padding: 10px;
    background: white;
    border-radius: 8px;
}

.message-input {
    flex: 1;
}

.send-button {
    width: 80px;
    height: 80px;
    padding: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.send-button i {
    font-size: 24px;
    margin-bottom: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .chat-container {
        padding: 10px;
    }

    .header h1 {
        font-size: 2em;
    }

    .chat-box {
        padding: 15px;
    }

    .chat-content {
        height: calc(100vh - 250px);
    }

    .input-area {
        flex-direction: column;
    }

    .send-button {
        width: 100%;
        height: 40px;
        flex-direction: row;
    }

    .send-button i {
        margin: 0 4px 0 0;
    }
}

/* 自定义滚动条 */
::-webkit-scrollbar {
    width: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb {
    background: #67c23a;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #85ce61;
}
</style> 